package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmNewsDto;
import com.zhentao.model.wemedia.dto.WmNewsPageReqDto;
import com.zhentao.model.wemedia.pojo.WmMaterial;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.model.wemedia.pojo.WmNewsMaterial;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsService;
import com.zhentao.service.WmNewsTaskService;
import com.zhentao.utils.common.WemediaConstants;
import com.zhentao.utils.common.WmUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class WmNewsServiceImpl implements WmNewsService{
    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;


    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //0.条件判断
        if(dto == null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2、把参数封装
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        // 3、补全属性
        wmNews.setUserId(WmUserThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable(1);
        if(dto.getStatus()==1){
            wmNews.setSubmitedTime(new Date());
        }

        //4、获取文章封面 todo
        if (dto.getImages()!=null && dto.getImages().size()>0){
            // 判断图片路径不为空
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }else{
            wmNews.setImages("http://192.168.183.128:19001/zhentaozixun/ba70bf0b-21ac-4fe2-9b20-f2d0cbee1cdf780.jpg");
        }

        // 处理tinyint 不能是负数
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO){
            dto.setType((short)4);
            wmNews.setType(4);

        }

        // 5、添加数据库
        // 判断是新增操作还是修改
        if (dto.getId() == null){
            // 如果id为空，id自增，则为新增
            wmNewsMapper.insert(wmNews);
        }else {
            // 修改
            Integer newsId = dto.getId();
            QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(WmNewsMaterial::getNewsId,newsId);
            wmNewsMaterialMapper.delete(queryWrapper);
            // 修改
            wmNewsMapper.updateById(wmNews);
        }

        // 新增关联
        // 处理封面// 图片是自己上传的
        if (dto.getType() !=4){
            List<String> images = dto.getImages();

            List<Integer> mids = new ArrayList<>();

            for (String img : images) {
                QueryWrapper<WmMaterial> materQ = new QueryWrapper<>();
                materQ.lambda().eq(WmMaterial::getUrl,img);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(materQ);
                mids.add(wmMaterial.getId());
            }
            // 把关系维护进去
            System.out.println("wmNews-id:------"+wmNews.getId());
            if (!mids.isEmpty() && mids.size()>0){
                wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
            }

        }else {
            // 自动获取封面
            //如何自动获取到封面  从内容里面获取
            /**
             * {
             *     type:"text",value:"34435"
             * }
             * {type:"image",value:"url"}
             */
            List<String> images = new ArrayList<>();

            List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);// 指定要转换的类型
            for (Map map : maps) {
                // 传递过来的是个图片
                if (map.get("type").equals("image")){
                    // 把获取到的图片保存在images
                    images.add((String) map.get("value"));
                }
            }

            if (images.size() == 0){
               // 此时内容里是没有图片的 面是没有4的局部的  0  1  3；   没有图片，布局就是0
                wmNews.setType(Integer.valueOf(WemediaConstants.WM_NEWS_TYPE_IMAGE));
                WmNews wmNews1 = new WmNews();
                wmNews1.setId(wmNews.getId());
                wmNews1.setType(Integer.valueOf(WemediaConstants.WM_NEWS_NONE_IMAGE));
                wmNewsMapper.updateById(wmNews1);
            }else {
                //内容里面是有图片的   把图片设置成封面
                // size=1  type=1  size=2 type=1 size=3 type=3 size=4 type=3
                if (images.size()==1 || images.size()==2){
                    // 修改type =1
                    WmNews wmNews1 = new WmNews();
                    wmNews1.setId(wmNews.getId());
                    wmNews1.setType(Integer.valueOf(WemediaConstants.WM_NEWS_SINGLE_IMAGE));

                    // 1、news 表里面的images 字段
                    String newsImages = StringUtils.join(images, ",");

                    wmNews1.setImages(newsImages);
                    wmNewsMapper.updateById(wmNews1);

                    List<Integer> mids = new ArrayList<>();
                    for (String img : images) {
                        // 2、处理素材和news的关系
                        QueryWrapper<WmMaterial> materQ = new QueryWrapper<>();
                        materQ.lambda().eq(WmMaterial::getUrl,img);
                        WmMaterial wmMaterial = wmMaterialMapper.selectOne(materQ);

                        mids.add(wmMaterial.getId());
                    }
                    // 把关系维护进去
                    wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
                } else if (images.size()>=3) {
                    // todo
                    // 修改type =3
                    WmNews wmNews1 = new WmNews();
                    wmNews1.setId(wmNews.getId());
                    wmNews1.setType(Integer.valueOf(WemediaConstants.WM_NEWS_MANY_IMAGE));

                    // 1、news 表里面的images 字段
                    String newsImages = StringUtils.join(images, ",");

                    wmNews1.setImages(newsImages);
                    wmNewsMapper.updateById(wmNews1);

                    List<Integer> mids = new ArrayList<>();
                    for (String img : images) {
                        // 2、处理素材和news的关系
                        QueryWrapper<WmMaterial> materQ = new QueryWrapper<>();
                        materQ.lambda().eq(WmMaterial::getUrl,img);
                        WmMaterial wmMaterial = wmMaterialMapper.selectOne(materQ);
                        mids.add(wmMaterial.getId());
                    }
                    // 把关系维护进去
                    wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
                }

            }



        }

        //处理内容与素材直接的关系  从里面里面吧素材获取到url -- id  添加操作

        if (dto.getStatus()==1){
            wmNewsAutoScanService.autoScanWnMews(wmNews.getId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override //获取内容列表
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1、检查参数
        dto.checkParam();
        //2、分页查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //1、userid
        queryWrapper.lambda().eq(WmNews::getUserId,WmUserThreadLocalUtil.getUser().getId());
        //2.频道
        queryWrapper.lambda().eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //3.状态
        queryWrapper.lambda().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //4关键字
        queryWrapper.lambda().eq(dto.getKeyword() != null, WmNews::getLabels, dto.getKeyword());

        //5、时间范围
        if (dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
            queryWrapper.lambda().between(WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        page = wmNewsMapper.selectPage(page, queryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(),dto.getSize(),Integer.valueOf(page.getTotal()+""));

        pageResponseResult.setCode(200);
        pageResponseResult.setErrorMessage("请求成功");
        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }
}